include Java
require 'pp'
require 'rubygems'
require 'xmlsimple'
require 'gookup/common/usefull_extensions'
require 'gookup/system/settings_container'
require 'gookup/reader/reader_helper'
require 'gookup/http/http_handler'

class Reader
  include_all(%w(httpclient httpclient.methods) , 'org.apache.commons')
  include ReaderHelper
  include HttpHandler

  attr_reader :sid

  def login(user, pass)
    post=PostMethod.new('https://www.google.com/accounts/ClientLogin')
    data=[['service', 'reader'], ['Email', user], ['Passwd', pass], ['source', 'mozzila'], ['continue', 'http://www.google.com/']]
    data.each{|pair|post.addParameter(NameValuePair.new(pair.first,pair.second))}
    response,code=call_http post
    @sid=nil or raise Exception.new('Failed to log in into reader!') if (response.match('BadAuthentication') or code!=200)# or due to left side nil
    @sid=response.split('=')[1].chomp.gsub('LSID', '')
  end

  def fetch_data
    get=GetMethod.new('http://www.google.com/reader/api/0/subscription/list')
    get.getParams().setCookiePolicy('ignoreCookies')
    get.setRequestHeader("Cookie", "SID="+@sid)
    @subscriptions,code=call_http get
  end


  def persist
    result = XmlSimple.xml_in(@subscriptions)
    subs_hashes=result.list.first.object
    entries=[]
    subs_hashes.each{|entry| entries << to_relevant_hash(entry)}
    xml=produce_xml(entries)
    File.open(Settings[:output]+'/google-reader-subscriptions.xml', 'w') do |file|
      file.puts xml
    end
  end

end